#include "myc.h"

void typetree(struct tree *tree) {
	if (!tree) return;
	struct func *func;
	switch(tree->toket) {
	case -2:
		if (isdigit(*tree->to.token->str)) {
			tree->toket=2;
			tree->to.val=toktoint(tree->to.token);
			tree->type.bt=tint;
			tree->type.pt=0;
		} else if (is_letter(*tree->to.token->str)) {
			struct var *var=find_var(tree->to.token);
			if (!var) tokerror(tree->to.token,tree->to.token->next,"undefined var");
			tree->type=var->type;
			tree->to.var=var;
			tree->toket=3;
		} else if (*tree->to.token->str=='\'') {
			tree->type.bt=tchar;
			tree->type.pt=0;
			tree->toket=4;
			char res=tree->to.token->str[1];
			if (res=='\\') switch (tree->to.token->str[2]) {
			case 'n': res='\n'; break;
			case 'r': res='\r'; break;
			case 't': res='\t'; break;
			case '0': res='\0'; break;
			case '\\': res='\\'; break;
			case '\'': res='\''; break;
			default: error("invalid escape sequence");
			}
			tree->to.vchar=res;
		} else if (*tree->to.token->str=='"') {
			tree->type.bt=tchar;
			tree->type.pt=1;
			tree->toket=5;
		} else tokerror(tree->to.token,tree->to.token->next,"cannon parse");
		break;
	case -1:
		if ((func=find_func(tree))) {
			tree->to.func=func;
			if (func->type.bt==tsame) {
				tree->type=find_same(tree,func);
				tree->type.pt+=func->type.pt;
				tree->type.lv=func->type.lv;
			} else tree->type=func->type;
			tree->toket=1;
		} else treerror(tree,"undefined function");
	}
}
